package com.excemly.library.controller;

import com.excemly.library.common.ApiResponse;
import com.excemly.library.entity.User;
import com.excemly.library.service.UserService;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/users")
@CrossOrigin(origins = "http://localhost:8080")
public class UserController {

    private final UserService userService;

    public UserController(UserService userService) {
        this.userService = userService;
    }

    // 获取用户列表（分页）
    @GetMapping
    public ApiResponse getUsers(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) String keyword) {
        try {
            Pageable pageable = PageRequest.of(page, size);
            Page<User> userPage = userService.findUsers(keyword, pageable);

            Map<String, Object> response = new HashMap<>();
            response.put("data", userPage.getContent());
            response.put("total", userPage.getTotalElements());
            response.put("totalPages", userPage.getTotalPages());

            return ApiResponse.success("用户列表获取成功", response);
        } catch (Exception e) {
            return ApiResponse.error(500, "获取用户列表失败: " + e.getMessage());
        }
    }

    // 获取单个用户
    @GetMapping("/{id}")
    public ApiResponse getUserById(@PathVariable Long id) {
        User user = userService.findById(id);
        if (user == null) {
            return ApiResponse.error(404, "用户不存在");
        }
        return ApiResponse.success("用户获取成功", user);
    }

    // 创建用户
    @PostMapping
    public ApiResponse createUser(@RequestBody User user) {
        if (userService.existsByUsername(user.getUsername())) {
            return ApiResponse.error(400, "用户名已存在");
        }
        User createdUser = userService.createUser(user);
        return ApiResponse.success("用户创建成功", createdUser);
    }

    // 更新用户
    @PutMapping("/{id}")
    public ApiResponse updateUser(@PathVariable Long id, @RequestBody User user) {
        if (!userService.existsById(id)) {
            return ApiResponse.error(404, "用户不存在");
        }
        user.setId(id);
        User updatedUser = userService.updateUser(user);
        return ApiResponse.success("用户更新成功", updatedUser);
    }

    // 删除用户
    @DeleteMapping("/{id}")
    public ApiResponse deleteUser(@PathVariable Long id) {
        if (!userService.existsById(id)) {
            return ApiResponse.error(404, "用户不存在");
        }
        userService.deleteUser(id);
        return ApiResponse.success("用户删除成功", null);
    }
}